package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.text.TextUtils;


import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.websocket.Symbol;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.MoveCoordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CoinChart;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.Core;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.MInteger;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.RetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


class RSILayer extends BasicLayer
{
	protected final double m_dbNone = Double.MIN_VALUE;
	private int beginIdx;//用于存储第一个指标第一个值的位置
	private String m_rsi1 = "",m_rsi2 = "",m_rsi3 = "";
	private String m_lastrsi1 = "",m_lastrsi2 = "",m_lastrsi3 = "";
	private int m_color1 = 0xFF4A86EA,m_color2 = 0xFFFF72A5,m_color3 = 0xFFFFA200,m_color0 = 0xFF808080;
	private int m_period1 = 6, m_period2 = 12, m_period3 = 24;

	public RSILayer()
	{
		super();
	}

	@Override
	public Coordinate createCoordinate()
	{
		return new MoveCoordinate();
	}

	@Override
	public boolean onCalculateData()
	{
		ArrayList<String> params = new ArrayList<>(Arrays.asList("6", "24", "12"));//FDTStorage.getInstance().getArray(SaveKey.CHART_INDICATOR_RSI + "param", SaveKey.CHART_INDICATOR_PARAM);
		if (params != null)
		{
			int param1 = !TextUtils.isEmpty(params.get(0)) ? Integer.parseInt(params.get(0)) : 6;
			int param2 = !TextUtils.isEmpty(params.get(1)) ? Integer.parseInt(params.get(1)) : 12;
			int param3 = !TextUtils.isEmpty(params.get(2)) ? Integer.parseInt(params.get(2)) : 24;

			int[] rsi_params = {param1,param2,param3};
			Arrays.sort(rsi_params);
			m_period1 = rsi_params[0];
			m_period2 = rsi_params[1];
			m_period3 = rsi_params[2];

		}
//		testMacd();
		//获得数据源
		List<CandleData> tDataList = m_callback.getCandleDataList();
		int tListSize = tDataList.size();
		List<CandleData> tList = new ArrayList<CandleData>();
		double[] closes = new double[tListSize];

		for (int ii = 0; ii < tListSize; ii++)
		{
			closes[ii] = tDataList.get(ii).getDbClose();
		}
		//准备计算数组
		double[] rsi_a = new double[tListSize];
		double[] rsi_b = new double[tListSize];
		double[] rsi_c = new double[tListSize];

		MInteger outBegIdx = new MInteger();
		MInteger outNbElement = new MInteger();

		Core taLib = CoinChart.getTaLib();
		RetCode retCode = taLib.rsi(0,closes.length-1,closes,m_period1,outBegIdx,outNbElement,rsi_a);
		RetCode retCode1 = taLib.rsi(0,closes.length-1,closes,m_period2,outBegIdx,outNbElement,rsi_b);
		RetCode retCode2 = taLib.rsi(0,closes.length-1,closes,m_period3,outBegIdx,outNbElement,rsi_c);
		//得到结果数组,结果为有值的部分开始如0.006747350439404443 0.010591595301185919 0.0027601354459569905 -0.03422737187350222 -0.09373321549064784 -0.12136830634374718 -0.12757081986248053 -0.1250403123559245 -0.11954476938285197 -0.04594994628476812 0.009701854832457002 0.06010755762170561 0.09747712313834 0.13895129756983238 0.171272192598785 0.18158545677729165 0.15978420503275714 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
		//outBegIdx为是第几个开始的，outNbElement为有效的数字个数 ，如73个元素，那么outBegIdx为33，outNbElement为40 26-1+9-1=33

		CandleData candle = null;

		for (int i = 0; i < tListSize; i++)
		{
			candle = tDataList.get(i);

			if (i >= m_period3)
			{
				candle.setDbOpen(rsi_a[i - m_period1]);
				candle.setDbClose(rsi_b[i - m_period2]);
				candle.setDbHigh(rsi_c[i - m_period3]);
			}
			else if (i >= m_period2)
			{
				candle.setDbOpen(rsi_a[i - m_period1]);
				candle.setDbClose(rsi_b[i - m_period2]);
				candle.setDbHigh(100);
			}
			else if (i >= m_period1)
			{
				candle.setDbOpen(rsi_a[i - m_period1]);
				candle.setDbClose(100);
				candle.setDbHigh(100);
			}
			else
			{
				candle.setDbOpen(100);
				candle.setDbClose(100);
				candle.setDbHigh(100);
			}
		}

		return true;
	}


	protected int getDataStartIndex()
	{
		return getMoveStartIndex() > beginIdx ? getMoveStartIndex() : beginIdx;
	}

	/**
	 * 获取数据的移动位置
	 * @return
	 */
	protected int getMoveStartIndex()
	{
		Coordinate tCoordinate = m_callback.getCoordinate();
		if(tCoordinate != null)
		{
			return tCoordinate.getStartIndex();
		}
		return 0;
	}

	@Override
	public Layer.ChartTypeEnum getLayerTypeEnum()
	{
		return Layer.ChartTypeEnum.RSI;
	}

	public List<CandleData> convertDate(List<CandleData> pList)
	{
		return pList;
	}

	@Override
	public void drawYesterClose(Canvas pCanvas, Paint pPaint)
	{
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		//获取坐标系
		Coordinate tCoordinate = m_callback.getCoordinate();
		//转化处理数据
		List<CandleData> tDataList = convertDate(m_callback.getCandleDataList());

		//定义初始化文本
		String tCloseText = null;
		String tOpenText = null;
		String tHighText = null;
		String tLowText = null;
		String tTimeText = null;
		String tValueText = null;
		String tVolumnText = null;
		int tXPoint = pPoint.x;


		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();
//			int tStartIndex = tCoordinate.getStartIndex();

			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();
			// float tYFirstposition = tCoordinate.getYFirstPosition();
			float tYMaxValue = tCoordinate.getMaxValue();
			float tYMinValue = tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
			float tYValueLength = tCoordinate.getValueHeight();
			// float tYValueLength = tCoordinate.getYInterval() *
			// tCoordinate.getYIntervalCount();

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;

			float tCurrentYPosition1 = 0.f;
			float tTempYPosition1 = 0.f;
			float tCurrentXPosition1 = 0.f;
			float tTempXPosition1 = 0.f;

			float tCurrentYPosition2 = 0.f;
			float tTempYPosition2 = 0.f;
			float tCurrentXPosition2 = 0.f;
			float tTempXPosition2 = 0.f;

			int m_bDigit = m_callback.getDigit();

			Symbol symbol = m_callback.getCoordinate().tSymBol;

			float tLineWidth = 2.f;
			pPaint.setAntiAlias(true);

			boolean tStartDraw = false;

			int tDotColor = BaseApp.getApp().getResources().getColor(R.color.sys_even);
			int tCulOffset = 1;

			int dataStart = getDataStartIndex(); //tStartIndex + getStartIndex();

			int moveStart = getMoveStartIndex();
			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(moveStart+displayCount,tListSize);//不能超出数据集宽度
//			FDTLogUtils.d("tingchart",getLayerTypeEnum()+"layer from draw tStartIndex"+dataStart+" to mincount"+minCount);
			if(dataStart > tListSize)//如果数据量不足以算出一个值
			{
				return;
			}
			CandleData candle = null;
			for (int i = dataStart; i < minCount; i++)
			{
				//如果收盘价为空就跳过
				candle = tDataList.get(i);
				if (candle.getDbClose() == m_dbNone || candle.getDbHigh() == m_dbNone || candle.getDbOpen() == m_dbNone)
				{
					continue;
				}

				pPaint.setColor(m_callback.getColor());
				pPaint.setStrokeWidth(tLineWidth);

				float trsi1 = (float) candle.getDbOpen();
				float trsi2 = (float) candle.getDbClose();
				float trsi3 = (float) candle.getDbHigh();

				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition = tCurrentYPosition;
				tCurrentYPosition = tYFirstposition - ((trsi1 - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition1 = tCurrentXPosition1;
				tCurrentXPosition1 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition1 = tCurrentYPosition1;
				tCurrentYPosition1 = tYFirstposition - ((trsi2 - tYMinValue) * tYValueLength / tYValueDist);

				tTempXPosition2 = tCurrentXPosition2;
				tCurrentXPosition2 = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition2 = tCurrentYPosition2;
				tCurrentYPosition2 = tYFirstposition - ((trsi3 - tYMinValue) * tYValueLength / tYValueDist);


				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2)) || ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2))
				{
					float tValueaa = (tYFirstposition - pPoint.y) * tYValueDist / tYValueLength + tYMinValue;
//					FDTLogUtils.d("tingtouch","tValueaa"+tValueaa);
					m_rsi1 = FormatUtil.getFormatString(trsi1,m_bDigit + 1);
					m_rsi2 = FormatUtil.getFormatString(trsi2,m_bDigit + 1);
					m_rsi3 = FormatUtil.getFormatString(trsi3,m_bDigit + 1);
					ChartData.ChartPeroid tChartType = m_callback.getChartType();
					tValueText = FormatUtil.getFormatString(tValueaa, m_bDigit);
					tTimeText = getDisplayX(tChartType, tDataList.get(i));

					tXPoint = (int) tCurrentXPosition;
				}

				if (tStartDraw)
				{
					RectF tRectF = tCoordinate.getLayerRectF();

					pPaint.setColor(m_color1);
					drawLine(pCanvas, pPaint, tCurrentYPosition, tTempYPosition, tCurrentXPosition, tTempXPosition, tCulOffset, tRectF);
					pPaint.setColor(m_color2);
					drawLine(pCanvas, pPaint, tCurrentYPosition1, tTempYPosition1, tCurrentXPosition1, tTempXPosition1, tCulOffset, tRectF);
					pPaint.setColor(m_color3);
					drawLine(pCanvas, pPaint, tCurrentYPosition2, tTempYPosition2, tCurrentXPosition2, tTempXPosition2, tCulOffset, tRectF);
				}
				else
				{
					tStartDraw = true;
				}

				if (tDataList.get(i).m_bDrawDot)
				{
					pPaint.setColor(tDotColor);
					pCanvas.drawCircle(tCurrentXPosition, tCurrentYPosition, tLineWidth * 2, pPaint);
				}

				if(i == minCount - 1)
				{
					if(candle != null)
					{
						m_lastrsi1 = FormatUtil.getFormatString(candle.getDbOpen(),m_bDigit + 1);
						m_lastrsi2 = FormatUtil.getFormatString(candle.getDbClose(),m_bDigit + 1);
						m_lastrsi3 = FormatUtil.getFormatString(candle.getDbHigh(),m_bDigit + 1);
					}
				}
			}
		}

		setCrossData(pCanvas, pPaint, tTimeText, tValueText, new Point(tXPoint, pPoint.y));

	}

	private void drawLine(Canvas pCanvas, Paint pPaint, float tCurrentYPosition, float tTempYPosition, float tCurrentXPosition, float tTempXPosition, int tCulOffset, RectF tRectF)
	{
		pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);

//		boolean tTempUpper = (tRectF.top - tCulOffset) <= tTempYPosition ? false : true;
//		boolean tTempLowwer = (tRectF.bottom + tCulOffset) >= tTempYPosition ? false : true;
//		boolean tCurrentUpper = (tRectF.top - tCulOffset) <= tCurrentYPosition ? false : true;
//		boolean tCurrentLowwer = (tRectF.bottom + tCulOffset) >= tCurrentYPosition ? false : true;
//
//		if (!tTempUpper && !tTempLowwer && !tCurrentUpper && !tCurrentLowwer)
//		{
////						LogUtils.w("DrawLineA", "startX: " + tTempXPosition + " startY: " + tTempYPosition
////							+ " endX: " + tCurrentXPosition + " endY: " + tCurrentYPosition);
//
//			pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
//		}
//		else if ((tTempUpper || tTempLowwer) && !tCurrentUpper && !tCurrentLowwer)
//		{
//			float middle;
//			if (tTempUpper)
//			{
//				middle = tRectF.top;
//			}
//			else
//			{
//				middle = tRectF.bottom;
//			}
//			float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;
//
//			pCanvas.drawLine(tTempX, middle, tCurrentXPosition, tCurrentYPosition, pPaint);
//		}
//		else if ((tCurrentUpper || tCurrentLowwer) && !tTempUpper && !tTempLowwer)
//		{
//			float middle;
//			if (tCurrentUpper)
//			{
//				middle = tRectF.top;
//			}
//			else
//			{
//				middle = tRectF.bottom;
//			}
//			float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;
//
//			pCanvas.drawLine(tTempXPosition, tTempYPosition, tTempX, middle, pPaint);
//		}
//		else
//		{
//		}
	}

	private String getDigitString(String value, int digit)
	{
		if (! TextUtils.isEmpty(value))
		{
			try
			{
				value = FormatUtil.getFormatString(Double.parseDouble(value), digit);
			}
			catch (Exception e)
			{
			}
		}
		else
		{
			value = "";
		}

		return value;
	}

	private float getScale(float start, float end, float middle)
	{
		return (start - middle) / (start - end);
	}

	private void resetIndicatorData()
	{
		m_rsi1 = "";
		m_rsi2 = "";
		m_rsi3 = "";
		m_lastrsi1 = "";
		m_lastrsi2 = "";
		m_lastrsi3 = "";
	}

	/**
	 * draw layer left－top text
	 * 获取指标值进行显示
	 * @param pCanvas
	 * @param pPaint
	 */
	@Override
	public void drawFloatIndicatorText(boolean longtouch,Canvas pCanvas, Paint pPaint)
	{

		if (!m_callback.needFloatIndicatorText())
		{
			return;
		}

		List<CandleData> tDataList = m_callback.getCandleDataList();
		if(tDataList == null || tDataList.size() == 0)
		{
			resetIndicatorData();
		}

		Coordinate tCoordinate = m_callback.getCoordinate();
		RectF tLayerRect = tCoordinate.getLayerRectF();

		float tLeftPadding = DimentionsUtil.dp2px(0);
		float tButtomPadding = DimentionsUtil.dp2px(1);
		float tWordPadding = DimentionsUtil.dp2px(10);

		String indicatorText0 = String.format("RSI(%s,%s,%s)", m_period1, m_period2, m_period3);
		String indicatorText1;
		String indicatorText2;
		String indicatorText3;
		if (longtouch)
		{
			indicatorText1 = "RSI" + m_period1 + ":" + m_rsi1;
			indicatorText2 = "RSI" + m_period2 + ":" + m_rsi2;
			indicatorText3 = "RSI" + m_period3 + ":" + m_rsi3;
		}
		else
		{
			indicatorText1 = "RSI" + m_period1 + ":" + m_lastrsi1;
			indicatorText2 = "RSI" + m_period2 + ":" + m_lastrsi2;
			indicatorText3 = "RSI" + m_period3 + ":" + m_lastrsi3;
		}
		pPaint.setAntiAlias(true);
		float textSize = DimentionsUtil.dp2px(10);
		pPaint.setTextSize(textSize);
		float tTxtWidth0 = pPaint.measureText(indicatorText0);
		float tTxtWidth1 = pPaint.measureText(indicatorText1);
		float tTxtWidth2 = pPaint.measureText(indicatorText2);

		pPaint.setColor(m_color0);
		pCanvas.drawText(indicatorText0, tLayerRect.left + tLeftPadding, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color1);
		pCanvas.drawText(indicatorText1, tLayerRect.left + tLeftPadding + tWordPadding + tTxtWidth0, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color2);
		pCanvas.drawText(indicatorText2, tLayerRect.left + tLeftPadding + tWordPadding * 2 + tTxtWidth0 + tTxtWidth1, tLayerRect.top + tButtomPadding + textSize, pPaint);
		pPaint.setColor(m_color3);
		pCanvas.drawText(indicatorText3, tLayerRect.left + tLeftPadding + tWordPadding * 3 + tTxtWidth0 + tTxtWidth1 + tTxtWidth2, tLayerRect.top + tButtomPadding + textSize, pPaint);

	}
}
